import { ref } from 'vue'
import configRouter from '@/config/config.router.js'
import cache from '@/utils/cache.js'
import configApp from '@/config/config.app.js'

export function useAuth(_configRouter = configRouter) {
    const configRouter = ref(_configRouter)

    // 检查目标页面是否需要登录
    function requiresAuth(url) {
        return configRouter.value.needLogin.some((pattern) => new RegExp(pattern).test(url))
    }

    // 检查目标页面是否在白名单中
    function isInWhiteList(url) {
        return configRouter.value.whiteList.some((pattern) => new RegExp(pattern).test(url))
    }

    // 检查目标页面是否在tabbar中
    function isInTabbar(url) {
        return configRouter.value.tabbar.some((tabbarUrl) => url.includes(tabbarUrl))
    }

    // 通用的登录检查函数
    function checkAuth(url) {
        if (requiresAuth(url) && !isInWhiteList(url) && !cache.get(configApp.accessToken)) {
            uni.redirectTo({
                url: `${configRouter.value.loginPage}?redirectUrl=${encodeURIComponent(url)}`,
            })
            return false // 阻止导航
        }
        return true // 允许导航
    }

    return {
        configRouter,
        checkAuth,
        isInTabbar,
    }
}
